import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by heyiyong on 2016/5/7.
 */
public class Utils {
    public static void writeXml(Set<Map.Entry<String, String>> entrySet, File file) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
        StringBuilder stringBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<resources>\n");
        String lastName = "";
        for (Map.Entry<String, String> entry : entrySet) {
            String name = entry.getKey();
            if (!name.startsWith(lastName)) {
                stringBuilder.append("\n");
            }
            stringBuilder.append("\t<string name=\"").append(entry.getKey().toLowerCase()).append("\">").append(entry.getValue()).append("</string>\n");
//            stringBuilder.append("\t<item>@string/").append(entry.getKey().toLowerCase()).append("</item>").append("\n");
            lastName = name.substring(0, 5);
        }
        stringBuilder.append("</resources>");
        bufferedWriter.write(stringBuilder.toString(), 0, stringBuilder.length());
        bufferedWriter.close();
    }

    public static void writeProperties(Set<Map.Entry<String, String>> entrySet, File file) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
        StringBuilder stringBuilder = new StringBuilder("#此文件已进行排序\r\n");
        String lastName = "";
        for (Map.Entry<String, String> entry : entrySet) {
            String key = entry.getKey();
            if (!key.startsWith(lastName)) {
                stringBuilder.append("\n");
            }
            stringBuilder.append(entry.getKey().toLowerCase()).append("=").append(entry.getValue()).append("\n");
            lastName = key.substring(0, 5);
        }
        bufferedWriter.write(stringBuilder.toString(), 0, stringBuilder.length());
        bufferedWriter.close();
    }

    /**
     * 读取xml，并且能够读取嵌套的内容，但目前仅能读取一层
     * @param keyValMap
     * @param file
     * @throws DocumentException
     */
    public static void readXmlWithChild(Map<String, String> keyValMap, File file) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(file);
        Element root = document.getRootElement();
        String rootName = root.getName();
        Iterator<Element> iterator = root.elementIterator();
        while (iterator.hasNext()) {
            // name
            Element element = iterator.next();
            String name = element.attribute("name").getValue();

            // value
            // 目前只支持一个子element，例如：<string name="login_forget_password"><u>忘记密码？</u></string>
            Iterator<Element> children = element.elementIterator();
            String tagName = null;
            if (children.hasNext()) {
                Element child = children.next();
                tagName = child.getQName().getName();
            }
            String value = element.getStringValue();
            value = Utils.filter(value);
            if (tagName != null) {
                System.out.println("注意：name为" + name + "的标签，有一个子标签为" + tagName + "，现在已经兼容！");
                value = "<" + tagName + ">" + value + "</" + tagName + ">";
            }
            keyValMap.put(name, value);
        }
    }

    public static void iosRead(String filePath, Map<String, String> map) throws Exception {
        URL resource = XmlSorter.class.getResource(filePath);
        File file = new File(resource.getFile());
        SAXReader reader = new SAXReader();
        Document document = reader.read(file);
        Element root = document.getRootElement();
        Iterator<Element> iterator = root.elementIterator();
        while (iterator.hasNext()) {
            Element element = iterator.next();
            String name = element.attribute("name").getValue();
            String value = element.getStringValue();
            map.put(name, value);
        }
    }

    /**
     * 过滤xml的tag值
     * 过滤：trim、换行
     *
     * @param value tag值
     * @return 过滤后的tag值
     */
    public static String filter(String value) {
//        value = value.replaceAll("\n", "");
        value = value.replaceAll("etc...", "…"); // choose_addr_hint_detail_addr
        value = value.replaceAll("'", "\\\\'"); // can't的单引号
        value = value.replaceAll("<", "&lt;");
        value = value.replaceAll(">", "&gt;");
        value = value.replaceAll("Q&S", "Q&amp;S");
        value = value.trim();
        return value;
    }
}
